//
//  WebView.swift
//  MD5
//
//  Created by 郑东喜 on 2016/11/22.
//  Copyright © 2016年 郑东喜. All rights reserved.
//

import UIKit
import WebKit


class WebView: UIViewController,WKUIDelegate,WKScriptMessageHandler,WKNavigationDelegate {

    
    var webView: WKWebView!
    
 
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.edgesForExtendedLayout = UIRectEdge()

        
        //wkwebview相关配置
        let configuration = WKWebViewConfiguration()
        configuration.preferences = WKPreferences()

        configuration.preferences.javaScriptEnabled = true
        
        // 默认是不能通过JS自动打开窗口的，必须通过用户交互才能打开
        configuration.preferences.javaScriptCanOpenWindowsAutomatically = false
        
        let userContentController = WKUserContentController()

        
        
        configuration.userContentController = userContentController
        
        let preferences = WKPreferences()
        preferences.javaScriptCanOpenWindowsAutomatically = true
        preferences.minimumFontSize = 10.0
        configuration.preferences = preferences
        
        
        
        webView = WKWebView.init(frame: view.bounds, configuration: configuration)
        


        let url = Bundle.main.url(forResource: "WKWebViewMessageHandler",withExtension: "html")
        self.webView.load(URLRequest.init(url: url!))
        self.view.addSubview(self.webView)

        view.addSubview(webView)
        
        webView.uiDelegate = self
        webView.navigationDelegate = self

    }
    
    /**
     *  JS 调用 swift 时 webview 会调用此方法
     *
     *  @param userContentController  webview中配置的userContentController 信息
     *  @param message                JS执行传递的消息
     */

    func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
        print(message.body)
        let msg = message.name
        
        if  msg == "shareWeixinInfo" {
            print("shareWeixinInfo")
            
            let artController = UIAlertController(title: "测试", message: message.body as? String, preferredStyle: .alert)
            
            artController.addAction(UIAlertAction(title: "取消", style: .cancel, handler: nil))
            self.present(artController, animated: true, completion: nil)
        }
    }
}



extension WebView {

    //确定js
    func webView(_ webView: WKWebView, runJavaScriptConfirmPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (Bool) -> Void) {
        let alert = UIAlertController(title: "Tip", message: message, preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "Ok", style: .default, handler: { (_) -> Void in
            completionHandler(true)
        }))
        alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: { (_) -> Void in
            completionHandler(false)
        }))
        
        self.present(alert, animated: true, completion: nil)
    }
    
    //alert js
    func webView(_ webView: WKWebView, runJavaScriptAlertPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping () -> Void) {
        
        let alertController = UIAlertController(title: "tip", message: message, preferredStyle: .alert)
        
        alertController.addAction(UIAlertAction(title: "Ok", style: .default, handler: { (_) in
            completionHandler()
        }))
        
        self.present(alertController, animated: true, completion: nil)
    }
    
    //alert iuput
    func webView(_ webView: WKWebView, runJavaScriptTextInputPanelWithPrompt prompt: String, defaultText: String?, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (String?) -> Void) {
        let alert = UIAlertController(title: prompt, message: defaultText, preferredStyle: .alert)
        
        alert.addTextField { (textField: UITextField) -> Void in
            textField.textColor = UIColor.red
        }
        alert.addAction(UIAlertAction(title: "Ok", style: .default, handler: { (_) -> Void in
            completionHandler(alert.textFields![0].text!)
        }))
        
        self.present(alert, animated: true, completion: nil)
    }

    
    //获取
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        print("\((#file as NSString).lastPathComponent):(\(#line))")
        print(self.webView.title as Any)
        self.navigationItem.title = self.webView.title
    }
    
    

}
